package Phaser_7;
import java.util.concurrent.Phaser;
public class 基本用法_多阶段任务协调 {
    public static void main(String[] args) {
        final int TASK_COUNT = 5;
        final Phaser phaser = new Phaser(TASK_COUNT) {
            protected boolean onAdvance(int phase, int registeredParties) {
                System.out.println("===== 阶段 " + phase + " 完成 =====");
                return registeredParties == 0; // 返回true表示终止
            }
        };
        for (int i = 0; i < TASK_COUNT; i++) {
            final int taskId = i;
            new Thread(new Runnable() {
                public void run() {
                    for (int phase = 0; phase < 3; phase++) {
                        try {
                            System.out.println("任务-" + taskId + " 开始阶段 " + phase);
                            Thread.sleep((long)(Math.random() * 500 + 100));
                            System.out.println("任务-" + taskId + " 完成阶段 " + phase);
                            phaser.arriveAndAwaitAdvance(); // 等待其他任务
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    phaser.arriveAndDeregister(); // 退出注册
                }
            }).start();
        }
    }
}